package com.cytangaa.display;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;

import com.cytanaa.youlike.Preferences;
import com.cytanaa.youlike.R;
import com.cytangaa.displaysize.DisplaySize;
import com.cytangaa.youlike.database.DbAdapter;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;

public class HdPlayer extends Activity {
	private static final String fb_id = "416965195026704";
	private SharedPreferences mPrefs;
	DisplaySize mDisplaySize;
	String SrcPath1 = "rtsp://v1.cache5.c.youtube.com/CiILENy73wIaGQkgHx9w8aRdHhMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp";
	String youtubeLink = null;
	String thumbnailLink, description, VideoId, viewCount, date = null;
	String title = null;
	WebView webview;
	public Button hd_basket_btn, hd_share_btn, full_screen_btn;
	String duration = null;
	public static final String likeLink2 = "http://www.facebook.com/YouLikePage";
	public static final String photoLink = "http://www.freeimagehosting.net/t/fi8ps.jpg";

	private Facebook facebook = new Facebook(fb_id);
	DbAdapter db;

	/** Called when the activity is first created. */
	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		super.onCreate(savedInstanceState);
		db = new DbAdapter(this);
		Log.v("onCreate", "onCreate");

		getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
		LayoutInflater inflator = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflator.inflate(R.layout.recommended_title, null);
		this.getActionBar().setDisplayShowCustomEnabled(true);
		this.getActionBar().setDisplayShowTitleEnabled(false);
		this.getActionBar().setBackgroundDrawable(
				new ColorDrawable(Color.parseColor("#ffff0000")));
		this.getActionBar().setCustomView(v);
		setContentView(R.layout.hd_player);
		//setAutoOrientationEnabled(this.getContentResolver(), true);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		Bundle bundle = this.getIntent().getExtras();
		SrcPath1 = bundle.getString("link");
		youtubeLink = bundle.getString("youtubeLink");
		thumbnailLink = bundle.getString("thumbnailLink");
		// description = bundle.getString("description");
		title = bundle.getString("title");
		VideoId = bundle.getString("id");
		duration = bundle.getString("duration");
		viewCount = bundle.getString("view_count");
		date = bundle.getString("uploaded_date");
		Log.v("duration", "duration is " + duration);
		Log.v("viewCount", "viewCount is " + viewCount);
		Log.v("VideoId", "VideoId is " + VideoId);
		mPrefs = getSharedPreferences("facebook_session", MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);
		Log.i("postToWall",
				"facebook.setAccessToken(access_token), and access_token=="
						+ access_token);
		if (access_token != null) {
			facebook.setAccessToken(access_token);
			Log.i("postToWall",
					"facebook.setAccessToken(access_token), and facebook.isSessionValid()=="
							+ facebook.isSessionValid());
		}
		if (expires != 0) {
			facebook.setAccessExpires(expires);
			Log.i("postToWall", "facebook.setAccessExpires(expires)" + expires);
		}
		Log.i("iframe", " before findViewById");

		webview = (WebView) findViewById(R.id.web_view_player_vertical);
		webview.clearCache(true);
		webview.clearHistory();
		webview.getSettings().setJavaScriptEnabled(true);
		webview.getSettings().setPluginState(PluginState.ON);
		webview.getSettings().setPluginsEnabled(true);
		webview.getSettings().setLoadWithOverviewMode(true);// completely zoomed
															// out
		webview.getSettings().setUseWideViewPort(true);
		webview.getTouchables();
		// webview.getSettings().setBuiltInZoomControls(false);
		// webview.getSettings().setDisplayZoomControls(false);
		webview.setBackgroundColor(Color.parseColor("#00000000"));

		/*
		 * code for initializing the layout
		 */
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int heightPix = displaymetrics.heightPixels;
		int widthPix = displaymetrics.widthPixels;
		mDisplaySize = new DisplaySize(this);

		Display display = getWindowManager().getDefaultDisplay();
		int[] widthHeight = new int[2];
		widthHeight = mDisplaySize.getDisplaySize(display);
		int width = widthHeight[0];
		Log.i("iframe", " before iframe");
		String emdLink = "http://www.youtube.com/embed/" + VideoId;
		Log.i("iframe", " before loadData, youtubeLink: " + emdLink);

		LayoutParams lp = new RelativeLayout.LayoutParams(width,
				(width / 4) * 3);
		lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		webview.setLayoutParams(lp);
		hd_share_btn = (Button) findViewById(R.id.hd_share_btn);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				widthPix / 2, heightPix / 7);
		layoutParams.addRule(RelativeLayout.BELOW,
				R.id.web_view_player_vertical);
		hd_share_btn.setLayoutParams(layoutParams);

		hd_basket_btn = (Button) findViewById(R.id.hd_basket_btn);
		RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(
				widthPix / 2, heightPix / 7);
		layoutParams2.addRule(RelativeLayout.RIGHT_OF, R.id.hd_share_btn);
		layoutParams2.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.hd_share_btn);
		hd_basket_btn.setLayoutParams(layoutParams2);
		
		full_screen_btn = (Button) findViewById(R.id.full_screen_btn);
		RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(
				widthPix / 2, heightPix / 7);
		layoutParams3.addRule(RelativeLayout.BELOW, R.id.hd_share_btn);
		layoutParams3.addRule(RelativeLayout.ALIGN_RIGHT, R.id.hd_share_btn);
		full_screen_btn.setLayoutParams(layoutParams3);
		

		webview.setWebChromeClient(new WebChromeClient());
		webview.setWebViewClient(new WebViewClient());

		// webview.loadUrl("http://google.com");
		webview.loadUrl(emdLink);

	}

	@SuppressLint("SetJavaScriptEnabled")
	public void FullScreenFunction(){
			Log.v("FullScreenFunction", "durationPass :: " + duration);
			Log.v("FullScreenFunction", SrcPath1);
			Bundle bundle = new Bundle();
			bundle.putString("duration", duration);
			bundle.putString("link", SrcPath1);
			bundle.putString("youtubeLink", youtubeLink);
			bundle.putString("thumbnailLink", thumbnailLink);
			bundle.putString("title", title);
			bundle.putString("id", VideoId);
			bundle.putString("view_count", viewCount);
			bundle.putString("uploaded_date", date);
			// bundle.putParcelableArray("thumbnails", bitmap);
			Log.v("FullScreenFunction", "start");

			Intent myIntent = new Intent(this, HdPlayerHorizontal.class);
			myIntent.putExtras(bundle);
			startActivity(myIntent);
			//finish();
			//Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
		
	}

	public void Share(View v) {
		postToWall();
	}	
	public void FullScreen(View v) {
		FullScreenFunction();
	}

	public void WatchLater(View v) {
		db.open();

		Cursor cursor = db.getTitle(VideoId);
		Log.i("checking", "checking duration : " + duration);

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Log.i("checking", "checking checking 1");
		Date addDate = new Date();
		Log.i("checking", "checking checking 1");
		String mdate = dateFormat.format(addDate);
		if (cursor.moveToFirst()) {
			Log.i("checking", "checking update 1");
			// boolean dbResult=db.updateTitle(VideoId, date, "nil", title,
			// thumbnailLink, duration, youtubeLink,
			// SrcPath1, viewCount, addDate);
			Toast.makeText(this, "Added Before", Toast.LENGTH_SHORT).show();

		} else {
			Log.i("checking", "checking create 1");
			Log.i("checking", "checking date 1" + date);
			Log.i("checking", "checking VideoId 1" + VideoId);
			Log.i("checking", "checking title 1" + title);
			Log.i("checking", "checking thumbnailLink 1" + thumbnailLink);
			Log.i("checking", "checking duration 1" + duration);
			Log.i("checking", "checking SrcPath1 1" + SrcPath1);
			Log.i("checking", "checking viewCount 1" + viewCount);
			Log.i("checking", "checking mdate 1" + mdate);

			long dbResult = db.insertVideo(date, VideoId, "nil", title,
					thumbnailLink, duration, youtubeLink, SrcPath1, viewCount,
					mdate);
			Log.i("checking", "checking checking Long" + dbResult);
			Toast.makeText(this, "Added Successfully", Toast.LENGTH_SHORT)
					.show();

		}

		db.close();

	}

	/**
	 * Facebook sharing handler
	 */
	public void postToWall() {
		Bundle parameters = new Bundle();
		if (youtubeLink == null) {
			youtubeLink = SrcPath1;
		}
		Log.i("postToWall", "youtubeLink == " + youtubeLink);

		parameters.putString("message", "");
		parameters.putString("link", youtubeLink);
		parameters.putString("description", description);
		parameters.putString("picture", thumbnailLink);

		if (facebook.isSessionValid()) {
			Log.i("postToWall", "mFacebook.isSessionValid()");
			// mAsyncRunner.request("me/feed", parameters, "POST", new
			// FacebookPostListener(), null);

			facebook.dialog(this, "feed", parameters, new DialogListener() {
				@Override
				public void onFacebookError(FacebookError e) {
					Log.i("onFacebookError", "youtubeLink == " + e);

				}

				@Override
				public void onError(DialogError e) {
					Log.i("onFacebookError", "onCancel == " + e);

				}

				@Override
				public void onComplete(Bundle values) {
				}

				@Override
				public void onCancel() {

				}
			});

		} else {
			Log.i("postToWall", "mFacebook.isSessionValid() is not true");
			Log.i("postToWall",
					"mFacebook.getAccessToken(): " + facebook.getAccessToken());

			facebook.authorize(this,
					new String[] { "email", "publish_stream" },
					new DialogListener() {

						@Override
						public void onCancel() {
							// Function to handle cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							// Function to handle complete event
							// Edit Preferences and update facebook acess_token
							SharedPreferences.Editor editor = mPrefs.edit();
							// mFacebook.setAccessToken("tooken");
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
							Log.i("postToWall", "mFacebook.getAccessToken(): "
									+ facebook.getAccessToken());
							Log.i("postToWall",
									"mFacebook.getAccessExpires(): "
											+ facebook.getAccessExpires());
						}

						@Override
						public void onError(DialogError error) {
							// Function to handle error
							Log.i("postToWall", "mFacebook.onError(): " + error);

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Function to handle Facebook errors
							Log.i("postToWall", "mFacebook.onFacebookError(): "
									+ fberror);
						}

					});
		}

	}

	/*
	 * Orientation Changed
	 */

	public static void setAutoOrientationEnabled(ContentResolver resolver,
			boolean enabled) {
		Settings.System.putInt(resolver,
				Settings.System.ACCELEROMETER_ROTATION, enabled ? 1 : 0);
	}



	@Override
	public void onStart() {
		super.onStart();
		Log.v("onStart", "onStart");

	}

	// TODO
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(Menu.NONE, Menu.FIRST + 1, 5, "Setting").setIcon(
				android.R.drawable.ic_menu_preferences);
		menu.add(Menu.NONE, Menu.FIRST + 2, 5, "Like us on Facebook").setIcon(
				R.drawable.like_menu);
		menu.add(Menu.NONE, Menu.FIRST + 3, 5, "Share the fun").setIcon(
				R.drawable.share_menu);

		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			Intent i = new Intent(this, Preferences.class);
			startActivityForResult(i, 1);

			break;
		case Menu.FIRST + 2:
			// Intent i = new Intent(this, Preferences.class);
			Intent browserIntent2 = new Intent(Intent.ACTION_VIEW,
					Uri.parse(likeLink2));
			startActivity(browserIntent2);
			break;

		case Menu.FIRST + 3:
			// Intent i = new Intent(this, Preferences.class);
			postUsToWall();
			break;
		}
		return false;
	}

	/**
	 * Facebook sharing handler
	 */
	public void postUsToWall() {
		Bundle parameters = new Bundle();

		parameters.putString("message", "");
		parameters.putString("link", likeLink2);
		parameters.putString("description", "Good Stuff!!!!");
		parameters.putString("picture", photoLink);

		if (facebook.isSessionValid()) {
			Log.i("postToWall", "mFacebook.isSessionValid()");
			// mAsyncRunner.request("me/feed", parameters, "POST", new
			// FacebookPostListener(), null);

			facebook.dialog(this, "feed", parameters, new DialogListener() {
				@Override
				public void onFacebookError(FacebookError e) {
					Log.i("onFacebookError", "youtubeLink == " + e);

				}

				@Override
				public void onError(DialogError e) {
					Log.i("onFacebookError", "onCancel == " + e);

				}

				@Override
				public void onComplete(Bundle values) {
				}

				@Override
				public void onCancel() {

				}
			});

		} else {
			Log.i("postToWall", "mFacebook.isSessionValid() is not true");
			Log.i("postToWall",
					"mFacebook.getAccessToken(): " + facebook.getAccessToken());

			facebook.authorize(this,
					new String[] { "email", "publish_stream" },
					new DialogListener() {

						@Override
						public void onCancel() {
							// Function to handle cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							// Function to handle complete event
							// Edit Preferences and update facebook acess_token
							SharedPreferences.Editor editor = mPrefs.edit();
							// mFacebook.setAccessToken("tooken");
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
							Log.i("postToWall", "mFacebook.getAccessToken(): "
									+ facebook.getAccessToken());
							Log.i("postToWall",
									"mFacebook.getAccessExpires(): "
											+ facebook.getAccessExpires());
						}

						@Override
						public void onError(DialogError error) {
							// Function to handle error
							Log.i("postToWall", "mFacebook.onError(): " + error);

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Function to handle Facebook errors
							Log.i("postToWall", "mFacebook.onFacebookError(): "
									+ fberror);
						}

					});
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		Log.i("onPuase", "onPuase");
		//setAutoOrientationEnabled(this.getContentResolver(), false);
		try {
			Log.i("in onpause", "onpause try");
			Class.forName("android.webkit.WebView")
					.getMethod("onPause", (Class[]) null)
					.invoke(webview, (Object[]) null);
			Log.i("in onpause", "onpause tried");


		} catch (ClassNotFoundException cnfe) {
		} catch (NoSuchMethodException nsme) {
		} catch (InvocationTargetException ite) {
		} catch (IllegalAccessException iae) {
		} catch (Exception  all) {
			Log.i("Exception", "Exception : "+all );

		}
		Log.i("onPuase", "b 4 webview");
		//webview.clearDisappearingChildren();
		//webview.stopLoading();
		//webview.clearCache(true);
		//webview.clearView();
		//webview.destroyDrawingCache();
		//webview.destroy();

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//Toast.makeText(this, "onDestroy", Toast.LENGTH_LONG).show();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		webview.clearDisappearingChildren();
		webview.stopLoading();
		webview.clearCache(true);
		webview.clearView();
		webview.destroyDrawingCache();
		webview.destroy();
		//setAutoOrientationEnabled(this.getContentResolver(), false);
		//Toast.makeText(this, "onStop", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.v("onResume", "onResume");

	}
	
	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onRestart() {
		super.onRestart();
		Log.v("onRestart", "onRestart");
		//setAutoOrientationEnabled(this.getContentResolver(), true);
		String emdLink = "http://www.youtube.com/embed/" + VideoId;
        Log.v("onRestart", "portrait");

        setContentView(R.layout.hd_player);
        webview = (WebView) findViewById(R.id.web_view_player_vertical);
        Log.v("onRestart", "find webview");

        /*
         * code for initializing the layout
         */
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int heightPix = displaymetrics.heightPixels;
        int widthPix = displaymetrics.widthPixels;
        mDisplaySize = new DisplaySize(this);

        Display display = getWindowManager().getDefaultDisplay();
        int[] widthHeight = new int[2];
        widthHeight = mDisplaySize.getDisplaySize(display);
        int width = widthHeight[0];
        Log.i("iframe", " before iframe");

        LayoutParams lp = new RelativeLayout.LayoutParams(width,
                        (width / 4) * 3);
        lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        webview.setLayoutParams(lp);
        hd_share_btn = (Button) findViewById(R.id.hd_share_btn);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                        widthPix / 2, heightPix / 7);
        layoutParams.addRule(RelativeLayout.BELOW,
                        R.id.web_view_player_vertical);
        hd_share_btn.setLayoutParams(layoutParams);

        hd_basket_btn = (Button) findViewById(R.id.hd_basket_btn);
        RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(
                        widthPix / 2, heightPix / 7);
        layoutParams2.addRule(RelativeLayout.RIGHT_OF, R.id.hd_share_btn);
        layoutParams2.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.hd_share_btn);
        hd_basket_btn.setLayoutParams(layoutParams2);
        
		full_screen_btn = (Button) findViewById(R.id.full_screen_btn);
		RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(
				widthPix / 2, heightPix / 7);
		layoutParams3.addRule(RelativeLayout.BELOW, R.id.hd_share_btn);
		layoutParams3.addRule(RelativeLayout.ALIGN_RIGHT, R.id.hd_share_btn);
		full_screen_btn.setLayoutParams(layoutParams3);
        webview.clearCache(true);
        webview.clearHistory();
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setPluginState(PluginState.ON);
        webview.getSettings().setPluginsEnabled(true);
        webview.getSettings().setLoadWithOverviewMode(true);// completely zoomed
                                                                                                                // out
        webview.getSettings().setUseWideViewPort(true);
        webview.getTouchables();
        // webview.getSettings().setBuiltInZoomControls(false);
        // webview.getSettings().setDisplayZoomControls(false);
        webview.setBackgroundColor(Color.parseColor("#00000000"));
        webview.setWebChromeClient(new WebChromeClient());
        webview.setWebViewClient(new WebViewClient());
        webview.loadUrl(emdLink);
		
		Log.v("onResume", "onResume 2");
	}

}
